package com.yuanqi.controller;

import com.yuanqi.domain.RetailSalesOrder;
import com.yuanqi.domain.CustomerType;
import com.yuanqi.service.RetailSalesOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 零售销售订单控制器
 */
@RestController
@RequestMapping("/api/retail/orders")
@CrossOrigin(origins = "*")
public class RetailSalesOrderController {
    
    @Autowired
    private RetailSalesOrderService retailSalesOrderService;
    
    /**
     * 创建销售订单
     */
    @PostMapping
    public ResponseEntity<RetailSalesOrder> createOrder(@RequestBody RetailSalesOrder order) {
        try {
            RetailSalesOrder createdOrder = retailSalesOrderService.createSalesOrder(order);
            return ResponseEntity.ok(createdOrder);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 更新销售订单
     */
    @PutMapping("/{id}")
    public ResponseEntity<RetailSalesOrder> updateOrder(@PathVariable Long id, @RequestBody RetailSalesOrder order) {
        try {
            order.setId(id);
            RetailSalesOrder updatedOrder = retailSalesOrderService.updateSalesOrder(order);
            return ResponseEntity.ok(updatedOrder);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 根据ID查找销售订单
     */
    @GetMapping("/{id}")
    public ResponseEntity<RetailSalesOrder> getOrder(@PathVariable Long id) {
        Optional<RetailSalesOrder> order = retailSalesOrderService.findById(id);
        return order.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 根据订单编码查找销售订单
     */
    @GetMapping("/by-code/{orderCode}")
    public ResponseEntity<RetailSalesOrder> getOrderByCode(@PathVariable String orderCode) {
        Optional<RetailSalesOrder> order = retailSalesOrderService.findByOrderCode(orderCode);
        return order.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 分页查找销售订单
     */
    @GetMapping
    public ResponseEntity<Page<RetailSalesOrder>> getOrders(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<RetailSalesOrder> orders = retailSalesOrderService.findAll(pageable);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 根据客户ID查找销售订单
     */
    @GetMapping("/customer/{customerId}")
    public ResponseEntity<List<RetailSalesOrder>> getOrdersByCustomerId(@PathVariable Long customerId) {
        List<RetailSalesOrder> orders = retailSalesOrderService.findByCustomerId(customerId);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 根据客户姓名查找销售订单
     */
    @GetMapping("/customer/name/{customerName}")
    public ResponseEntity<List<RetailSalesOrder>> getOrdersByCustomerName(@PathVariable String customerName) {
        List<RetailSalesOrder> orders = retailSalesOrderService.findByCustomerName(customerName);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 根据客户电话查找销售订单
     */
    @GetMapping("/customer/phone/{customerPhone}")
    public ResponseEntity<List<RetailSalesOrder>> getOrdersByCustomerPhone(@PathVariable String customerPhone) {
        List<RetailSalesOrder> orders = retailSalesOrderService.findByCustomerPhone(customerPhone);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 根据订单状态查找销售订单
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<RetailSalesOrder>> getOrdersByStatus(@PathVariable String status) {
        List<RetailSalesOrder> orders = retailSalesOrderService.findByOrderStatus(status);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 根据客户类型查找销售订单
     */
    @GetMapping("/customer-type/{customerType}")
    public ResponseEntity<List<RetailSalesOrder>> getOrdersByCustomerType(@PathVariable String customerType) {
        CustomerType customerTypeEnum = CustomerType.valueOf(customerType);
        List<RetailSalesOrder> orders = retailSalesOrderService.findByCustomerType(customerTypeEnum);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 根据日期范围查找销售订单
     */
    @GetMapping("/date-range")
    public ResponseEntity<List<RetailSalesOrder>> getOrdersByDateRange(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        try {
            LocalDateTime start = LocalDateTime.parse(startDate + "T00:00:00");
            LocalDateTime end = LocalDateTime.parse(endDate + "T23:59:59");
            List<RetailSalesOrder> orders = retailSalesOrderService.findByOrderDateBetween(start, end);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 更新订单状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<RetailSalesOrder> updateOrderStatus(
            @PathVariable Long id,
            @RequestParam String status,
            @RequestParam(defaultValue = "系统") String operatorName) {
        try {
            RetailSalesOrder order = retailSalesOrderService.updateOrderStatus(id, status, operatorName);
            return ResponseEntity.ok(order);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 处理订单
     */
    @PostMapping("/{id}/process")
    public ResponseEntity<RetailSalesOrder> processOrder(
            @PathVariable Long id,
            @RequestParam(defaultValue = "系统") String operatorName) {
        try {
            RetailSalesOrder order = retailSalesOrderService.processOrder(id, operatorName);
            return ResponseEntity.ok(order);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 发货
     */
    @PostMapping("/{id}/ship")
    public ResponseEntity<RetailSalesOrder> shipOrder(
            @PathVariable Long id,
            @RequestParam(defaultValue = "系统") String operatorName,
            @RequestParam(required = false) String shippingInfo) {
        try {
            RetailSalesOrder order = retailSalesOrderService.shipOrder(id, operatorName, shippingInfo);
            return ResponseEntity.ok(order);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 完成订单
     */
    @PostMapping("/{id}/complete")
    public ResponseEntity<RetailSalesOrder> completeOrder(
            @PathVariable Long id,
            @RequestParam(defaultValue = "系统") String operatorName) {
        try {
            RetailSalesOrder order = retailSalesOrderService.completeOrder(id, operatorName);
            return ResponseEntity.ok(order);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/{id}/cancel")
    public ResponseEntity<RetailSalesOrder> cancelOrder(
            @PathVariable Long id,
            @RequestParam String reason,
            @RequestParam(defaultValue = "系统") String operatorName) {
        try {
            RetailSalesOrder order = retailSalesOrderService.cancelOrder(id, reason, operatorName);
            return ResponseEntity.ok(order);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 删除销售订单
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteOrder(@PathVariable Long id) {
        try {
            retailSalesOrderService.deleteById(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 获取订单统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Object> getOrderStatistics() {
        Object statistics = retailSalesOrderService.getOrderStatistics();
        return ResponseEntity.ok(statistics);
    }
    
    /**
     * 生成订单编码
     */
    @GetMapping("/generate-code")
    public ResponseEntity<String> generateOrderCode() {
        String orderCode = retailSalesOrderService.generateOrderCode();
        return ResponseEntity.ok(orderCode);
    }
}
